package com.free.food.product.controller;

import com.free.food.core.domain.ResultVO;
import com.free.food.core.util.ResultUtil;
import com.free.food.product.dto.ProductInfoDTO;
import com.free.food.product.entity.ProductCategory;
import com.free.food.product.req.DecreaseStockReq;
import com.free.food.product.res.FindProductInfoRes;
import com.free.food.product.res.ProductRes;
import com.free.food.product.service.CategoryService;
import com.free.food.product.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019-02-08 12:25
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVO list() {
        //1. 查询已上架商品
        List<FindProductInfoRes> upList = productService.findUpAll();
        //2. 已上架类目
        List<Integer> typeList = upList.stream().map(FindProductInfoRes::getCategoryType).collect(Collectors.toList());
        //3. 查询类目信息
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(typeList);
        //4. 构造数据
        List<ProductRes> productResList = new ArrayList<>();
        for (ProductCategory category : productCategoryList) {

            ProductRes productRes = new ProductRes();
            productRes.setCategoryName(category.getCategoryName());
            productRes.setCategoryType(category.getCategoryType());

            List<ProductInfoDTO> productInfoDTOs = new ArrayList<>();
            for (FindProductInfoRes productInfo : upList) {
                if (category.getCategoryType().equals(productInfo.getCategoryType())) {
                    ProductInfoDTO productInfoDTO = new ProductInfoDTO();
                    BeanUtils.copyProperties(productInfo, productInfoDTO);
                    productInfoDTOs.add(productInfoDTO);
                }
            }
            productRes.setProductInfoDTOList(productInfoDTOs);

            productResList.add(productRes);
        }

        return ResultUtil.success(productResList);
    }

    /**
     * 获取商品列表
     *
     * @param productIdList
     * @return
     */
    @PostMapping("/listForOrder")
    public List<FindProductInfoRes> listForOrder(@RequestBody List<String> productIdList) {

        return productService.findByProductIdIn(productIdList);
    }

    /**
     * 减库存
     *
     * @param cartDTOList
     * @return
     */
    @PostMapping("/decreaseStock")
    public void decreaseStock(@RequestBody List<DecreaseStockReq> cartDTOList) {
        productService.decreaseStock(cartDTOList);
    }

}
